<template>
  <div 
    :class="[
      'bx-table',
      'bx-glass',
      {
        'bx-table--bordered': bordered,
        'bx-table--striped': striped,
        'bx-table--hoverable': hoverable,
        [`bx-table--${size}`]: size
      }
    ]"
  >
    <!-- 表格头部 -->
    <div v-if="$slots.header || title" class="bx-table__header">
      <slot name="header">
        <h3 class="bx-table__title">{{ title }}</h3>
      </slot>
    </div>

    <!-- 表格容器 -->
    <div class="bx-table__container">
      <table class="bx-table__table">
        <!-- 表头 -->
        <thead class="bx-table__thead">
          <tr>
            <th
              v-for="column in columns"
              :key="column.key || column.dataIndex"
              :class="[
                'bx-table__th',
                {
                  'bx-table__th--sortable': column.sorter,
                  'bx-table__th--sorted': sortedColumn === (column.key || column.dataIndex)
                }
              ]"
              :style="getColumnStyle(column)"
              @click="handleSort(column)"
            >
              <div class="bx-table__th-content">
                <span>{{ column.title }}</span>
                <div 
                  v-if="column.sorter"
                  class="bx-table__sorter"
                >
                  <BxIcon 
                    name="chevron-up"
                    :class="[
                      'bx-table__sort-icon',
                      {
                        'bx-table__sort-icon--active': sortedColumn === (column.key || column.dataIndex) && sortOrder === 'asc'
                      }
                    ]"
                  />
                  <BxIcon 
                    name="chevron-down"
                    :class="[
                      'bx-table__sort-icon',
                      {
                        'bx-table__sort-icon--active': sortedColumn === (column.key || column.dataIndex) && sortOrder === 'desc'
                      }
                    ]"
                  />
                </div>
              </div>
            </th>
          </tr>
        </thead>

        <!-- 表体 -->
        <tbody class="bx-table__tbody">
          <tr
            v-for="(record, index) in sortedData"
            :key="getRowKey(record, index)"
            :class="[
              'bx-table__tr',
              {
                'bx-table__tr--selected': selectedRowKeys.includes(getRowKey(record, index))
              }
            ]"
            @click="handleRowClick(record, index)"
          >
            <td
              v-for="column in columns"
              :key="column.key || column.dataIndex"
              :class="[
                'bx-table__td',
                column.className
              ]"
              :style="getColumnStyle(column)"
            >
              <slot 
                :name="column.key || column.dataIndex"
                :record="record"
                :index="index"
                :value="getColumnValue(record, column)"
              >
                {{ formatColumnValue(record, column) }}
              </slot>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 空状态 -->
      <div 
        v-if="!sortedData.length"
        class="bx-table__empty"
      >
        <slot name="empty">
          <BxEmpty description="暂无数据" />
        </slot>
      </div>

      <!-- 加载状态 -->
      <div 
        v-if="loading"
        class="bx-table__loading"
      >
        <BxLoading />
      </div>
    </div>

    <!-- 表格底部 -->
    <div 
      v-if="$slots.footer || pagination"
      class="bx-table__footer"
    >
      <slot name="footer">
        <BxPagination 
          v-if="pagination"
          v-bind="paginationProps"
          @change="handlePageChange"
        />
      </slot>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import BxIcon from '../basic/BxIcon.vue'
import BxLoading from './BxLoading.vue'
import BxEmpty from './BxEmpty.vue'
import BxPagination from '../navigation/BxPagination.vue'

export default {
  name: 'BxTable',
  components: {
    BxIcon,
    BxLoading,
    BxEmpty,
    BxPagination
  },
  props: {
    columns: {
      type: Array,
      default: () => [],
      required: true
    },
    dataSource: {
      type: Array,
      default: () => []
    },
    rowKey: {
      type: [String, Function],
      default: 'id'
    },
    selectedRowKeys: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    bordered: {
      type: Boolean,
      default: false
    },
    striped: {
      type: Boolean,
      default: false
    },
    hoverable: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: 'medium',
      validator: (value) => ['small', 'medium', 'large'].includes(value)
    },
    title: {
      type: String,
      default: ''
    },
    pagination: {
      type: [Boolean, Object],
      default: false
    }
  },
  emits: ['row-click', 'selection-change', 'sort-change', 'page-change'],
  setup(props, { emit }) {
    const sortedColumn = ref('')
    const sortOrder = ref('')

    const sortedData = computed(() => {
      let data = [...props.dataSource]
      
      if (sortedColumn.value && sortOrder.value) {
        const column = props.columns.find(col => 
          (col.key || col.dataIndex) === sortedColumn.value
        )
        
        if (column && column.sorter) {
          data.sort((a, b) => {
            const aValue = getColumnValue(a, column)
            const bValue = getColumnValue(b, column)
            
            if (typeof column.sorter === 'function') {
              return column.sorter(a, b) * (sortOrder.value === 'asc' ? 1 : -1)
            }
            
            // 默认排序逻辑
            if (aValue < bValue) return sortOrder.value === 'asc' ? -1 : 1
            if (aValue > bValue) return sortOrder.value === 'asc' ? 1 : -1
            return 0
          })
        }
      }
      
      return data
    })

    const paginationProps = computed(() => {
      if (typeof props.pagination === 'object') {
        return {
          total: props.dataSource.length,
          pageSize: 10,
          current: 1,
          ...props.pagination
        }
      }
      return {
        total: props.dataSource.length,
        pageSize: 10,
        current: 1
      }
    })

    const getRowKey = (record, index) => {
      if (typeof props.rowKey === 'function') {
        return props.rowKey(record, index)
      }
      return record[props.rowKey] || index
    }

    const getColumnValue = (record, column) => {
      const dataIndex = column.dataIndex
      if (!dataIndex) return ''
      
      // 支持嵌套属性，如 'user.name'
      return dataIndex.split('.').reduce((obj, key) => obj?.[key], record)
    }

    const formatColumnValue = (record, column) => {
      const value = getColumnValue(record, column)
      
      if (column.render && typeof column.render === 'function') {
        return column.render(value, record)
      }
      
      return value
    }

    const getColumnStyle = (column) => {
      const style = {}
      
      if (column.width) {
        style.width = typeof column.width === 'number' ? `${column.width}px` : column.width
      }
      
      if (column.align) {
        style.textAlign = column.align
      }
      
      return style
    }

    const handleSort = (column) => {
      if (!column.sorter) return
      
      const columnKey = column.key || column.dataIndex
      
      if (sortedColumn.value === columnKey) {
        // 切换排序方向
        if (sortOrder.value === 'asc') {
          sortOrder.value = 'desc'
        } else if (sortOrder.value === 'desc') {
          sortedColumn.value = ''
          sortOrder.value = ''
        } else {
          sortOrder.value = 'asc'
        }
      } else {
        sortedColumn.value = columnKey
        sortOrder.value = 'asc'
      }
      
      emit('sort-change', {
        column: columnKey,
        order: sortOrder.value
      })
    }

    const handleRowClick = (record, index) => {
      emit('row-click', record, index)
    }

    const handlePageChange = (page, pageSize) => {
      emit('page-change', page, pageSize)
    }

    return {
      sortedColumn,
      sortOrder,
      sortedData,
      paginationProps,
      getRowKey,
      getColumnValue,
      formatColumnValue,
      getColumnStyle,
      handleSort,
      handleRowClick,
      handlePageChange
    }
  }
}
</script>

<style scoped>
.bx-table {
  background: var(--bx-glass-bg);
  backdrop-filter: var(--bx-glass-blur);
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-large);
  overflow: hidden;
  font-family: var(--bx-font-family);
}

.bx-table__header {
  padding: 16px 20px;
  border-bottom: 1px solid var(--bx-glass-border);
  background: rgba(255, 255, 255, 0.02);
}

.bx-table__title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--bx-text-primary);
}

.bx-table__container {
  position: relative;
  overflow-x: auto;
}

.bx-table__table {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;
}

.bx-table__thead {
  background: rgba(255, 255, 255, 0.03);
}

.bx-table__th {
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: var(--bx-text-primary);
  border-bottom: 1px solid var(--bx-glass-border);
  position: relative;
}

.bx-table--small .bx-table__th {
  padding: 8px 12px;
  font-size: 13px;
}

.bx-table--large .bx-table__th {
  padding: 16px 20px;
  font-size: 16px;
}

.bx-table__th--sortable {
  cursor: pointer;
  user-select: none;
}

.bx-table__th--sortable:hover {
  background: var(--bx-glass-bg-hover);
}

.bx-table__th-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--bx-spacing-xs);
}

.bx-table__sorter {
  display: flex;
  flex-direction: column;
  gap: 1px;
}

.bx-table__sort-icon {
  font-size: 10px;
  color: var(--bx-text-tertiary);
  transition: color var(--bx-transition-medium);
}

.bx-table__sort-icon--active {
  color: rgba(0, 122, 255, 0.8);
}

.bx-table__tbody {
  /* 表体样式 */
}

.bx-table__tr {
  transition: background-color var(--bx-transition-medium);
}

.bx-table--hoverable .bx-table__tr:hover {
  background: var(--bx-glass-bg-hover);
}

.bx-table--striped .bx-table__tr:nth-child(even) {
  background: rgba(255, 255, 255, 0.02);
}

.bx-table__tr--selected {
  background: rgba(0, 122, 255, 0.1);
}

.bx-table__td {
  padding: 12px 16px;
  color: var(--bx-text-primary);
  border-bottom: 1px solid var(--bx-glass-border);
  word-break: break-word;
}

.bx-table--small .bx-table__td {
  padding: 8px 12px;
  font-size: 13px;
}

.bx-table--large .bx-table__td {
  padding: 16px 20px;
  font-size: 16px;
}

.bx-table--bordered .bx-table__th,
.bx-table--bordered .bx-table__td {
  border-right: 1px solid var(--bx-glass-border);
}

.bx-table--bordered .bx-table__th:last-child,
.bx-table--bordered .bx-table__td:last-child {
  border-right: none;
}

.bx-table__empty {
  padding: 40px 20px;
  text-align: center;
  color: var(--bx-text-tertiary);
}

.bx-table__loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

.bx-table__footer {
  padding: 16px 20px;
  border-top: 1px solid var(--bx-glass-border);
  background: rgba(255, 255, 255, 0.02);
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bx-table__header,
  .bx-table__footer {
    padding: 12px 16px;
  }
  
  .bx-table__th,
  .bx-table__td {
    padding: 8px 12px;
    font-size: 13px;
  }
  
  .bx-table--small .bx-table__th,
  .bx-table--small .bx-table__td {
    padding: 6px 8px;
    font-size: 12px;
  }
  
  .bx-table--large .bx-table__th,
  .bx-table--large .bx-table__td {
    padding: 12px 16px;
    font-size: 15px;
  }
  
  .bx-table__title {
    font-size: 15px;
  }
  
  .bx-table__empty {
    padding: 30px 16px;
  }
}
</style>

